package com.situ.mall.controller;

import com.situ.mall.pojo.Category;
import com.situ.mall.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class IndexController {
    @Autowired
    private ICategoryService categoryService;
    
    @Autowired
    private RedisTemplate redisTemplate;

    // http://127.0.0.1:8082/
    @RequestMapping("/")
    public String index(Model model) {
        // 1、首先从Redis缓存读取
        List<Category> topCategoryList = redisTemplate.opsForList().range("topCategoryList", 0, -1);
        // if (topCategoryList == null || topCategoryList.size() == 0)
        // 2、Redis中没有
        if (CollectionUtils.isEmpty(topCategoryList)) {
            System.out.println("Redis中没有topCategoryList，从数据库中读取");
            topCategoryList = categoryService.selectTopCategoryList();
            // 3、从数据库读取后，更新到Redis中
            redisTemplate.opsForList().rightPushAll("topCategoryList", topCategoryList);
        }

        List<Category> secondCategoryList = redisTemplate.opsForList().range("secondCategoryList", 0, -1);
        if (CollectionUtils.isEmpty(secondCategoryList)) {
            System.out.println("Redis中没有secondCategoryList，从数据库中读取");
            secondCategoryList = categoryService.selectSecondCategoryList();
            // 3、从数据库读取后，更新到Redis中
            redisTemplate.opsForList().rightPushAll("secondCategoryList", secondCategoryList);
        }

        model.addAttribute("topCategoryList", topCategoryList);
        model.addAttribute("secondCategoryList", secondCategoryList);
        return  "index";
    }
}
